(function($){
	var 
		hours	= 60*60,
		minutes	= 60;
	$.fn.countdown = function(prop){
		var options = $.extend({
			callback	: function(){},
			timestamp	: 0
		},prop);
		
		var left, h, m, s, positions;
		init(this, options);
		positions = this.find('.position');
		(function tick(){
			left = Math.floor((options.timestamp - (new Date())) / 1000);
			if(left < 0){
				left = 0;
			}
			h = Math.floor(left / hours);
			updateDuo(0, 1, h);
			left -= h*hours;
			m = Math.floor(left / minutes);
			updateDuo(2, 3, m);
			left -= m*minutes;
			s = left;
			updateDuo(4, 5, s);
			options.callback(h, m, s);
			setTimeout(tick, 1000);
		})();
		function updateDuo(minor,major,value){
			switchDigit(positions.eq(minor),Math.floor(value/10)%10);
			switchDigit(positions.eq(major),value%10);
		}
		return this;
	};
	function init(elem, options){
		elem.addClass('countdownHolder');
		$.each(['Hours','Minutes','Seconds'],function(i){
			$('<span class="count'+this+'">' +
				'<div>' +
				'<p class="position">' +
					'<span class="digit static">0</span>' +
				'</p>' +
				'</div>' +
				'<div>' +
				'<p class="position">' +
					'<span class="digit static">0</span>' +
				'</p>' +
				'</div>'
			).appendTo(elem);
			
			if(this!="Seconds"){
				elem.append('<p>:</p><span class="countDiv countDiv'+i+'"></span>');
			}
		});
	}
	function switchDigit(position,number){
		var digit = position.find('.digit')
		if(digit.is(':animated')){
			return false;
		}
		if(position.data('digit') == number){
			return false;
		}
		position.data('digit', number);
		
		var replacement = $('<span>',{
			'class':'digit',
			css:{
				top:0,
				opacity:0
			},
			html:number
		});
		digit
			.before(replacement)
			.removeClass('static')
			.animate({top:0,opacity:0},'fast',function(){
				digit.remove();
			})
		replacement
			.delay(100)
			.animate({top:0,opacity:1},'fast',function(){
				replacement.addClass('static');
			});
	}
})(jQuery);